package com.hotel.quertz;

import com.hotel.entity.Orders;
import com.hotel.service.OrderDetailService;
import com.hotel.service.OrdersService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Quartz任务
 *
 * @author Li
 * @date 2022/06/15
 */
public class QuartzDemo implements Job {

    /**
     * 订单服务
     */
    @Autowired
    private OrdersService ordersService;

    @Resource
    private OrderDetailService orderDetailService;

    /**
     * 执行
     *
     * @param jobExecutionContext 工作执行上下文
     * @throws JobExecutionException 任务执行异常
     */
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        List<Orders> unpaidOrder = ordersService.getUnpaidOrder();
        if (unpaidOrder.size() > 0) {
            unpaidOrder.forEach(orders -> {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String date = sdf.format(orders.getOrderTime());
                try {
                    Date parse = sdf.parse(date);
                    long time = 30*60*1000;
                    Date date1 = new Date(parse.getTime() + time);
                    Date date2 = new Date();
                    int i = date2.compareTo(date1);
                    if (i==1){
                        int delete = ordersService.deleteByOrderNumber(orders.getNumber());
                        int deleteDetails=orderDetailService.deleteOrderDetail(String.valueOf(orders.getId()));
                        System.err.println("已清除"+delete+"条未付款订单");
                        System.err.println("已清除"+deleteDetails+"条未付款订单详情");
                    }
                } catch (ParseException e) {
                    System.err.println("转换时间异常");
                }
            });
        }else {
            System.err.println("暂无逾期订单");
        }
    }
}